/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package TimeRecording.widgets;

import java.text.ParseException;
import java.util.Formatter;
import javax.swing.JFormattedTextField.AbstractFormatter;

/**
 *
 * @author dpatchett
 */
public class TimeFormatter extends AbstractFormatter {

    @Override
    public Object stringToValue(String text) throws ParseException {

        try {
            double hours;
            double minutes;

            if (text.indexOf(":") != -1) {

                String hoursText = text.substring(0, text.indexOf(":")).trim();
                if (hoursText.length() == 0) {
                    hoursText = "0";
                }
                String minutesText = text.substring(text.indexOf(":") + 1).trim();
                if (minutesText.length() == 0) {
                    minutesText = "0";
                }
                hours = Double.parseDouble(hoursText);
                minutes = Double.parseDouble(minutesText);

            } else {

                hours = Double.parseDouble(text.trim());
                minutes = 0.0f;
            }

            return hours + minutes / 60;

        } catch (NumberFormatException e) {
            
            invalidEdit();
            return null;
        }
    }

    @Override
    public String valueToString(Object value) throws ParseException {

        if (value == null) {
            return "";
        }
        double hours = Math.abs((Double)value);
        String sign = ((Double)value < 0) ? "-" : "";

        int intHours = (int)hours;
        int intMinutes = (int)Math.round((hours - intHours) * 60);

        return new Formatter().format("%0$s%2$02d:%3$02d",
                sign, intHours, intMinutes).toString();
    }
}
